import {defineStore} from "pinia";
import {treeList} from "@/api/system/permission/index.js";
import router from "@/router/index.js";
import {localSecretStorage} from "@/utils/ls.js";

export const usePermissionStore = defineStore("permission", {
    persist: {
        storage: localSecretStorage,
        pick: ["activeMenu", "opened", "activeRoute", "fixed"],
    },
    state: () => ({
        routes: [], // 动态路由
        permissions: [], // 权限列表
        activeMenu: "/", // 当前激活的菜单
        children: [], // 顶级导航菜单页的子菜单
        sidebarCollapsed: false,
        opened: [], // 打开的路由列表
        activeRoute: "/", // 当前激活的路由
        fixed: ["/"], // 固定的路由，不能被关闭
        hasInitialized: false,
        perms: []
    }),
    getters: {},
    actions: {
        async dynamicRoutes(menus, perms) {
            for (const menu of menus) {
                if (["M", "P"].indexOf(!menu.type) > -1) {
                    continue;
                }
                const {path, name, component, children, ...meta} = menu;
                let module = this.$modules[`/src/views/${component}.vue`];
                if (component === "" || component === null || module === undefined) {
                    module = this.$modules["/src/components/layout/style/View.vue"];
                }
                const route = {
                    path,
                    name,
                    component: module || this.$modules["/src/views/Error.vue"],
                    meta: meta,
                };
                router.addRoute(meta.parentName, route);
                perms.push({...menu});
                if (children && children.length > 0) {
                    await this.dynamicRoutes(children, perms);
                }
            }
        },
        hasPermission(perm) {
            if (this.perms.length<=0){
                this.perms = this.routes.map(route=>route.perms)
            }
            return this.perms.filter(p => p === perm).length === 1;
        },
        getRoute(key) {
            return (
                router.getRoutes().filter((i) => i.path === key)[0] || {
                    path: "/",
                    name: "dashboard",
                    meta: {
                        title: "首页",
                        icon: "HomeFilled",
                        parentName: "layout",
                    },
                }
            );
        },
        initialRoutes: async function () {
            this.permissions = await treeList();
            this.routes = [];
            // routes 表示动态路由
            console.info("---initialRoutes---", this.permissions)
            if (!this.permissions){
                ElMessage.error("初始化路由失败")
                return false;
            }
            // permissions 表示权限列表
            await this.dynamicRoutes(this.permissions, this.routes);
            return true;
        },
        updateActiveMenu: function (menu) {
            this.activeMenu = menu;
            this.activeRoute = menu;
        },
        updateActiveRoute: function (route) {
            this.activeRoute = route;
            this.activeMenu = route;
        },
        updateOpenedRoutes: function (path) { // 更新打开的路由
            let route = router.getRoutes().filter((r) => r.path === path)[0];
            if (!route) {
                return;
            }
            const has =
                this.fixed.find((r) => r === route.path) ||
                this.opened.find((r) => r === route.path);
            if (!has) {
                this.opened.push(route.path);
            }
        },
        removeOpenedRoute: function (path) {
            let route = router.getRoutes().filter((r) => r.path === path)[0];
            if (!route) {
                return;
            }
            // 当路由和激活路由一致时，激活路由需先变更
            if (this.activeRoute === route.path) {
                // 当前路由在数组中的位置
                const currentIndex = this.opened.findIndex((r) => r === route.path);
                // 如果当前路由不是最后一个，则跳转到下一个路由
                if (currentIndex < this.opened.length - 1) {
                    this.activeRoute = this.opened[currentIndex + 1];
                } else if (currentIndex > 0) {
                    // 如果是最后一个，则跳转到上一个路由
                    this.activeRoute = this.opened[currentIndex - 1];
                } else {
                    // 如果没有其他路由，则跳转到首页
                    this.activeRoute = this.fixed[0];
                }
            }
            // 从打开的路由中移除
            this.opened = this.opened.filter((r) => r !== route.path);
        },
        removeOpenedOther: function (path) {
            if (this.fixed.findIndex((r) => r === path) !== -1) {
                this.opened = [];
                this.activeRoute = path;
                return;
            }
            this.opened = [path];
            this.activeRoute = path;
        },
        removeOpened: function () {
            this.opened = [];
            this.activeRoute = this.fixed[0];
        },
    },
});
